package com.tiantian.quanminxiu.utils;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/***
        * Created by zhang on 2016/5/31.
        * <p>
* 自定义 json转换器
        */
public class JsonConverterFactory extends Converter.Factory {

    public static JsonConverterFactory create() {
        return create(new Gson());
    }

    public static JsonConverterFactory create(Gson gson) {
        return new JsonConverterFactory(gson);

    }

    private final Gson gson;

    private JsonConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return super.requestBodyConverter(type,parameterAnnotations,methodAnnotations,retrofit);
    }



    class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
        /**
         * 构造器
         */
        public JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {

        }

        /**
         * 转换
         *
         * @param responseBody
         * @return
         * @throws IOException
         */
        @Override
        public T convert(ResponseBody responseBody) throws IOException {

            String response = responseBody.string();
            try {
                JSONObject jsonObject = new JSONObject(response);
                if(jsonObject.optString("flag").equals("0")){
                    return (T)jsonObject;
                }else {
                    throw new RuntimeException("网络请求错误："+jsonObject.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                throw new RuntimeException("网络请求错误：数据解析出错");
            }
//            Log.i("xiaozhang", "解密的服务器数据：" + result);
        }

    }
}